package first.niuke.midding;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName NC15
 * @description:
 * @author: 荣燊
 * @create: 2021-04-08 16:04
 **/
public class NC15 {
    // 求二叉树的层序遍历
    public static void main(String[] args) {

    }

    public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        // write code here
        if (root == null) {
            return new ArrayList<>();
        }
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        //新建一个队列，将下一层加入到队列中，之后弹出遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            int n = queue.size();
            for (int i=0; i<n; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                list.add(node.val);
            }
            res.add(list);
        }
        return res;
    }


    class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    }
}
